package com.health.provider;

import com.health.security.SpringSecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @Classname UserLoginAuthenticationProvider
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/21 16:51
 * @Author RainGrd
 */
@Component
public class UserLoginAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    private SpringSecurityUserService springSecurityUserService;
    @Autowired
    private PasswordEncoder encoder;

    /**
     * 找到容器中的detailsService，并执行setUserDetailsService方法，完成赋值
     * <p>
     * 必须要给UserDetailsService赋值，否则会出现UnsatisfiedDependencyException
     */
    @Autowired
    private void setDetailsService() {
        setUserDetailsService(springSecurityUserService);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        String presentedPassword = authentication.getCredentials().toString();
        if (!encoder.matches(presentedPassword, userDetails.getPassword())) {
            throw new BadCredentialsException(messages.getMessage("badCredentials", "用户密码错误"));
        }
    }

}
